{extend name="normal_base" /}
{block name="navigation"}{/block}
{block name="css"}
<style>
    .layui-form-item {
        width: 100%;
    }

    .layui-table td {
        padding: 5px;
    }

    .layui-form-label {
        width: 100px;
    }

    #service_content_div{
        width: 80%;
    }

</style>
{/block}
{block name="body"}
<div class="x-body">
    <blockquote class="layui-elem-quote" style="color: #AAAAAA">Tip：输入客户关键字后会自动查询，如果查询不到，请检查是否已经录入该客户；合同编号为预计生成，最终生成的可能会大于该值，并且修改默认年份后，也会随之改变</blockquote>
    <form class="layui-form" id="from_id" method="POST" action="{:url('add')}">
        <div class="layui-form-item">
            <label class="layui-form-label" for="sign_company_code">
                <span class="x-red">*</span>&nbsp;合同签订公司：
            </label>
            <div class="layui-input-inline">
                <select name="sign_company_code" id="sign_company_code" lay-filter="sign_company" lay-verify="required|m_sign">
                    <option value=''>请选择</option>
                    {foreach name="sign_company_list" item="vo"}
                    <option value="{$vo.code}">{$vo.sign_company}</option>
                    {/foreach}
                </select>
            </div>
        </div>
        <div class="layui-form-item">


            <label for="contract-number-view" class="layui-form-label">
                合同编号：
            </label>
            <div class="layui-input-inline">
                <input type="text" id="contract-number-view" name="" required="" value="" disabled autocomplete="off" class="layui-input">
            </div>

            <div class="layui-form-mid layui-word-aux">
                <span style="color: #FF5722" id="show-contract-number">选择签订公司后自动生成预编号</span>
            </div>
        </div>

        <!--客户单位-->
        <div class="layui-form-item">
            <label for="company_name" class="layui-form-label">
                <span class="x-red">*</span>&nbsp;客户</i>：
            </label>

            <div class="layui-input-inline" id="show-customer-search" >
                <input type="text" id="company_name" name="company_name" placeholder="点击搜索..." value="" disabled required lay-verify=""
                       autocomplete="off" class="layui-input">
                <input type="hidden" id="customer_id" name="customer_id" value="0"/>
            </div>
            <div class="layui-form-mid layui-word-aux">
                若检索不到指定客户，请先 <a onclick="x_admin_show('添加用户','{:url("admin/customer/add")}')" style="cursor:pointer;color: #FFB800;">添加</a>！
            </div>
        </div>

        <!--合同年度-->
        <div class="layui-form-item">
            <label for="year" class="layui-form-label">
                <span class="x-red">*</span>&nbsp;合同年份：
            </label>
            <div class="layui-input-inline">
                <input class="layui-input" placeholder="" name="year" id="year" old-year="{:date('Y')}" value="{:date('Y')}" lay-verify="required|m_year">
            </div>
            <div class="layui-form-mid layui-word-aux">
                <span>四位年份</span>
            </div>
        </div>

        <!--业务类型-->
        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="x-red">*</span>&nbsp;业务类型：
            </label>
            <div class="layui-input-inline">
                <select name="class" id="class" lay-filter="class" lay-verify="required|m_type">
                    <option value=0>请选择类型</option>
                    <option value=></option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <div class="layui-input-inline">
                <select name="type" id="type" lay-filter="type" lay-verify="required|m_type">
                    <option value=0>请选择子类型</option>
                    <option value=></option>
                </select>
            </div>
        </div>

        <!--合同领取人-->
        <div class="layui-form-item">
            <label for="contract_receiver" class="layui-form-label">
                <span class="x-red">*</span>&nbsp;领取人：
            </label>
            <div class="layui-input-inline">
                <input type="text" id="contract_receiver" name="contract_receiver" lay-verify="required|m_input_short"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <!--营销经理-->
        <div class="layui-form-item">
            <label for="sale_manager" class="layui-form-label">
                <span class="x-red">*</span>&nbsp;营销经理：
            </label>
            <div class="layui-input-inline">
                <input type="text" id="sale_manager" name="sale_manager" required="" lay-verify="required|m_input_short"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <!--项目分组-->
        <div class="layui-form-item">
            <label class="layui-form-label">项目组：</label>
            <div class="layui-input-inline">
                <select name="project_group_id" id="project_group_id" lay-filter="sign_company_code">
                    <option value=''>请选择</option>
                    {foreach name='project_group_list' item='v' key="k"}
                    <option value="{$k}">{$v}</option>
                    {/foreach}
                </select>
            </div>
        </div>

        <!--项目名称-->
        <div class="layui-form-item">
            <label for="project_name" class="layui-form-label">
                项目名称：
            </label>
            <div class="layui-input-inline">
                <input type="text" id="project_name" name="project_name" lay-verify="m_input_long"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <!--项目负责人-->
        <div class="layui-form-item">
            <label for="project_manager" class="layui-form-label">
                项目负责人：
            </label>
            <div class="layui-input-inline">
                <input type="text" id="project_manager" name="project_manager" lay-verify="m_input_short"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <!--合同金额-->
        <div class="layui-form-item">
            <label for="contract_amount" class="layui-form-label">
                合同金额：
            </label>
            <div class="layui-input-inline">
                <input type="text" id="contract_amount" name="contract_amount" placeholder="￥" lay-verify="m_contract_amount"
                       autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">
                <span>元</span>
            </div>
        </div>

        <!--是否含税-->
        <div class="layui-form-item">
            <label class="layui-form-label">
                是否含税：
            </label>
            <div class="layui-input-inline">
                <input type="radio" name="is_include_tax"  value="1" title="是" checked="checked">
                <input type="radio" name="is_include_tax" value="0" title="否">
            </div>
        </div>

        <!--服务内容-->
        <div class="layui-form-item">
            <label for="service_content" class="layui-form-label">
                服务内容：
            </label>
            <div class="layui-input-inline" id="service_content_div">
                <textarea class="layui-textarea" id="service_content" name="service_content" style="display: none" lay-verify="m_service_content_text"></textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <label for="year" class="layui-form-label"></label>
            <div class="layui-input-block">
                <button  class="layui-btn" lay-filter="add" lay-submit="">
                    增加
                </button>

                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>

    </form>
</div>
{/block}

{block name="script"}
<script src="__JS__/jquery.raty.js"></script>
<script>
    layui.use(['form','layer','laydate', 'layedit'], function(){
        $ = layui.jquery;
        var layer = layui.layer;
        var layedit = layui.layedit;
        var form = layui.form
        var laydate = layui.laydate;

        //构建一个默认的编辑器
        var index = layedit.build('service_content',{
            tool: ['strong','italic','del','underline', '|', 'left', 'center', 'right']
            ,height: 300 //设置编辑器高度
        });

        //编辑器外部操作
        var active = {
            content: function(){
                //alert(layedit.getContent(index)); //获取编辑器内容
            }
            ,text: function(){
                //alert(layedit.getText(index)); //获取编辑器纯文本内容
            }
            ,selection: function(){
                //alert(layedit.getSelection(index));
            }
        };

        //自定义验证规则
        form.verify({
            m_input_short:function (value) {
                //验证长度是否超出限制,50个字
                if (value != "") {
                    if(value.length > 10){
                        return '内容长度超出限制，最多 10 个字';
                    }
                }
            },
            m_input_long:function (value) {
                //验证长度是否超出限制,255个字
                if (value != "") {
                    if(value.length > 255){
                        return '内容长度超出限制，最多 255 个字';
                    }
                }
            },
            m_year:function (value) {
                if (value != "") {
                    var emReg = /^[1-9]\d{3}$/;
                    if(!emReg.test(value)) {
                        return "请填写正确的年份!";
                    }
                } else {
                    return '请填写合同年份信息';
                }
            },
            m_type:function (value) {
                value = parseInt(value);
                if (value > 0) {
                    var emReg = /^\d{1,4}$/;
                    if(!emReg.test(value)) {
                        return "请选择正确的业务类型!";
                    }
                } else {
                    return '请选择业务类型!';
                }
            },
            m_contract_amount:function (value) {
                if (value != '') {
                    var emReg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
                    if (!emReg.test(value)) {
                        return "请输入正确的金额数据!";
                    }

                    if (value > 999999999) {
                        return "抱歉，输入正确的金额过大!";
                    }
                }
            },
            m_service_content_text:function (value) {
                if (value != "") {
                    if(value.length > 21000){
                        return '服务内容：长度超出限制，最多 21000 个字';
                    }
                }
                layedit.sync(index);//解决表单提交时，表单数据没该值的问题
            }
        });

        //执行一个laydate实例- 年度选择
        laydate.render({
            elem: '#year' //指定元素
            ,type: 'year'
            /*//,range: true //范围选择
             ,format: 'yyyy' //格式显示
             ,theme: 'default' //主题：default（默认简约）、molv（墨绿背景）、#颜色值（自定义颜色背景）、grid（格子主题）*/
            ,theme: 'molv'
            ,done: function(value, date, endDate) {
                //console.log(value); //得到日期生成的值，如：2017-08-18
                //console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                onChangeYear(value);
            }
        });

        //监听提交
        form.on('submit(add)', function(data){
            $("#from_id").ajaxSubmit({
                beforeSubmit:function () {

                    //表单提交前
                    //检查客户id是否已经被正确选择
                    var customer_id = $('#customer_id').val();
                    if (customer_id <= 0) {
                        layer.msg('请先选择客户！', {icon:5,time:1500});
                        return false;
                    }
                },
                success:function (data) {
                    //console.log(JSON.stringify(data));
                    if (data.code == 1) {
                        layer.msg(data.msg,{icon:5,time:1500});
                    } else {
                        layer.alert("添加成功", {icon: 6},function () {
                            // 获得frame索引
                            var index = parent.layer.getFrameIndex(window.name);
                            //关闭当前frame
                            parent.layer.close(index);
                            //刷新父层页面
                            parent.location.replace(parent.location.href);
                        });
                    }
                }
            });
            return false;
        });

        /*初始化业务类型*/
        init_contract_type(0);

        /*监听年份改变*/
        $('#year').bind('blur', function () {
            onChangeYear($('#year').val());
        });

        /*年份改变后重置编号*/
        function onChangeYear(new_data) {
            var year = $('#year');
            var old_data = year.attr('old-year');

            if (new_data != '') {
                var emReg = /^[1-9]\d{3}$/;
                if(!emReg.test(new_data)) {
                    layer.msg("请填写正确的年份!", {icon:5,time:1500});
                    return false;
                }

                var new_year = new_data.substring(2);

                if (old_data != new_data) {
                    //需要修改合同编号
                    var number_input = $('#contract-number-view');
                    var old_number = number_input.val();
                    var new_number = old_number.replace(/([A-Z]+-)\d{2}(\d{4})/g,"$1"+new_year+"$2");
                    //替换新编号
                    number_input.val(new_number);
                    year.attr("old-year", new_data);
                }
            }
        }

        /*模仿：xcity.js实现*/
        function init_contract_type(class_id) {
            var contract_type_list = {$contract_type_arr};
            var contract_class = $('#class');
            var contract_type = $('#type');
            var type_list = [];

            showClass(class_id);
            showType(type_list);

            function showClass(class_id) {
                var flag = false;
                contract_class.empty();
                contract_class.append("<option value='0'>请选择类型</option>")
                for (var i in contract_type_list) {
                    if (class_id > 0 && class_id == contract_type_list[i]['id']) {
                        //传入的大类型id能被找到，那么子类型的id需要被指定
                        flag = true;
                        type_list = contract_type_list[i]['son_list'];
                    }
                    contract_class.append("<option value='"+contract_type_list[i]['id']+"'>"+contract_type_list[i]['type']+"</option>")
                }

                if (!flag) {
                    type_list = [];
                }
            }

            function showType(type_list) {
                contract_type.empty();
                contract_type.append("<option value='0'>请选择子类型</option>")

                for (var i in type_list) {
                    contract_type.append("<option value='"+type_list[i]['id']+"'>"+type_list[i]['type']+"</option>")
                }
            }

            form.render('select');

            /*监听大类型的改变*/
            form.on('select(class)', function(data){
                class_id = data.value;
                showClass(class_id);
                contract_class.val(class_id);
                showType(type_list);
                form.render('select');
            });
        }

        /*点击弹出客户搜索页面*/
        $('#show-customer-search').bind('click', function () {
            layer.open({
                title:'客户搜索',
                type: 2,
                maxmin: true,
                area: [
                    $(window).width()*0.8 + 'px',
                    $(window).height()*0.8+ 'px'
                ],    //宽和高
                //skin: 'layui-layer-molv',     //加上边框：layui-layer-rim；深蓝：layui-layer-lan；墨绿：layui-layer-molv
                //offset: ['60px', '240px'],  //屏幕坐标位置
                shadeClose: true, //点击遮罩关闭
                closeBtn: 1,     //0:不显示关闭按钮; 1:显示关闭按钮
                content: '{:url("admin/customer/search")}',
                btn: ['确认','取消'],    //按钮1和按钮2的回调分别是yes和cancel，而从按钮3开始，则回调为btn3: function(){}，以此类推
                yes: function(index,layero){
                    //按钮【确认】的回调
                    var choose_customer_info = $.cookie('choose-search-cusotmer-info');//格式：客户id-客户名字
                    var choose_customer_info_arr = choose_customer_info.split('<==>');
                    var customer_id = choose_customer_info_arr[0];
                    var customer_name = choose_customer_info_arr[1];
                    $('#company_name').val(customer_name);
                    $('#customer_id').val(customer_id);

                    layer.close(index);
                },
                cancel: function(index){
                    //按钮【取消】的回调
                }
            });
        });

        form.on('select(sign_company)', function(data){
            /*获取该编号、该年份下的最新的序列号*/
            var code = data.value;
            var year = $('#year').val();//4位年份
            if (code != '' && year != '') {
                $.ajax({
                    type: "get",
                    url: "get_newest_sn?code="+code+"&year="+year,
                    dataType: "json",
                    success: function(data){
                        if (data.code == 0) {
                            var serial_number = data.msg;
                            year = year.substring(2);//年份

                            $('#contract-number-view').val(code+'-'+year + serial_number);
                        } else {
                            if (data.msg == '') {
                                layer.msg('获取最新合同编号失败！');
                            } else {
                                layer.msg(data.msg);
                            }
                        }
                    }, error: function(){
                        layer.msg("请求出错",{icon:5,time:1000});
                    }
                });

            }


        });
    });


</script>
{/block}